#include <unistd.h>
#include <ctype.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "log.h"

static char *logfilenames[]=
{
  "frunkd.log", "frunkd.err", "frunkd.dbg"
};

static FILE *fpLog[]=
{
  NULL, NULL, NULL
};

void WhiteToRealSpaces(char strText[])
{
  char *pch=&strText[0];

  do
  {
    if(isspace(*pch))
    {
      *pch=' ';
    }
  }
  while(*(pch++));
}

int Logf(int nLogType, const char *format, ...)
{
  va_list ap;
  int ret;
  time_t curtime;
  char *pstrTime;
  char strBuffer[1024];

  if(!fpLog[nLogType])
  {
    if(!(fpLog[nLogType]=fopen(logfilenames[nLogType], "a")))
    {
      return 0;
    }
  }

  curtime=time(NULL);
  pstrTime=strdup(ctime(&curtime));
  pstrTime[strlen(pstrTime)-1]='\0';
  fprintf(fpLog[nLogType], "[%s] ", pstrTime);
  free(pstrTime);

  va_start(ap, format);
  ret=vsnprintf(strBuffer, sizeof(strBuffer), format, ap);
  va_end(ap);

  WhiteToRealSpaces(strBuffer);
  fprintf(fpLog[nLogType], "%s\n", strBuffer);
  fflush(fpLog[nLogType]);
  return ret;
}

void LogClose(void)
{
  int i;

  for(i=0; i<3; i++)
  {
    if(fpLog[i])
    {
      fclose(fpLog[i]);
    }
  }
}
